package com.ljk;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;

class MyHandler extends DefaultHandler {
    private boolean inName = false;
    private boolean inAge = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equals("name")) {
            inName = true;
        } else if (qName.equals("age")) {
            inAge = true;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (inName) {
            System.out.println("姓名: " + new String(ch, start, length));
            inName = false;
        } else if (inAge) {
            System.out.println("年龄: " + new String(ch, start, length));
            inAge = false;
        }
    }



}

public class SaxUtil {
    public static void main(String[] args) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            InputStream inputStream = SaxUtil.class.getClassLoader().getResourceAsStream("example.xml");

            MyHandler handler = new MyHandler();
            parser.parse(inputStream, handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
